import '../public/index'
import url from '../data/url'
import request from '../data/request'
import { header } from '../data/config'
import store from 'store'

const base             = url.base,
      addPOSMerchant   = request.editPOSMerchant,
      getChannelList   = request.getChannelAll,
      getMoneyflowList = request.getMoneyflowList


// 页面标题
const title = 'POS商户信息',
      action = '修改';

let form = new Vue({
  el: '#form',
  data: () => {
    return ({
      id            : '',
      mchName       : '',
      mchNo         : '',
      channel       : '',
      channelList   : [],
      actionTag     : '',
      actionTagList : [],
      keyIndex      : '',
      authsn        : '',
      status        : '',
      keySnVersion  : '',
      isLock        : true
    })
  },
  mounted: function() {
    
    let that = this

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0
    })

    Promise
      .all([this.getChannel(), this.getMoneyflow()])
      .then((res) => {

        layer.close(loading)

        that.channelList   = res[0]
        that.actionTagList = res[1]
        that.isLock        = false

        let storeData = store.get('storeData')

        console.log(storeData)

        if (!storeData) {
          layer.msg('页面跳转错误', {
            icon: 5
          })

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)

          return
        }

        // 合并数据
        $.extend(that.$data, storeData, {
          channel   : _.find(that.channelList, (item) => (item.name === storeData.channel)).key,
          actionTag : _.find(that.actionTagList, (item) => (item.name === storeData.actionTag)).key,
        })

        valid()
      })
      .catch((error) => {
        console.log(error)

        layer.close(loading)
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })

  },
  methods: {
    // 获取渠道列表
    getChannel: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getChannelList,
              headers: header,
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function() {
            })

          })

    ),
    // 获取资金列表流向列表
    getMoneyflow: () => (
      new Promise((resolve, reject) => {

            $.ajax({
              url: base + getMoneyflowList,
              headers: header,
            })
            .done(function(res) {
              if (res.code === 0) {
                resolve(res.object)
              }
              reject(res.message)
            })
            .fail(function() {
              console.log("error")
              reject()
            })
            .always(function() {
            })

          })

    )
        
  }
})

function valid() {

  let form_valid,
      $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + addPOSMerchant,
        type: 'POST',
        contentType: 'application/json',
        headers: header,
        data: JSON.stringify({
          id           : form.id,
          mchName      : form.mchName,
          mchNo        : form.mchNo,
          channel      : form.channel,
          actionTag    : form.actionTag,
          keyIndex     : form.keyIndex,
          authsn       : form.authsn,
          status       : form.status,
          keySnVersion : form.keySnVersion
        })
      })
        .done(function(res) {
          console.log(res)

          if (res.code === -1 ) {
            layer.msg(res.message, {
              icon: 5
            })

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function(res) {
          console.log(res)

          layer.msg(`修改${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function(res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement:function(error, element) {
      error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      mchName: {
        required: true
      },
      mchNo: {
        required: true
      },
      channel: {
        required: true
      },
      actionTag: {
        required: true
      },
      keyIndex: {
        required: true
      },
      authsn: {
        required: true
      },
      status: {
        required: true
      },
      keySnVersion: {
        required: true,
        noSideSpace: true
      }
    }
  })

}